package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;


public class ChooseActivity extends AppCompatActivity {
    private static String TAG = "测试";
    private MapView mMapView;
    private String ip = "http://192.168.1.101";
    private ServiceFeatureTable serviceFeatureTable1;
    private Callout mCallout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        mMapView = findViewById(R.id.mapView);
        ArcGISMap map = new ArcGISMap();


        mMapView.setMap(map);
        mCallout = mMapView.getCallout();

        map.setInitialViewpoint(new Viewpoint(new Envelope(76.37606329842615, 40.243640421751806, 94.97012338238628, 48.93914272145798, SpatialReference.create(4326))));

        LayoutInflater inflater = LayoutInflater.from(ChooseActivity.this);
        View view = inflater.inflate(R.layout.input_view, null);
        EditText editText = view.findViewById(R.id.server_ip);

        new AlertDialog.Builder(ChooseActivity.this)
                .setTitle("请输入ArcGIS Server所在主机Ip")
                .setView(view)
                .setCancelable(false)
                .setPositiveButton("确定", (dialog, which) -> {
                    Log.e("ss", String.valueOf(editText.getText()));
                    ip = String.valueOf(editText.getText());
                    initLayer();
                    dialog.dismiss();
                }).create().show();
    }

    private void initLayer() {
        ArcGISMapImageLayer mapImageLayer = new ArcGISMapImageLayer(ip + getResources().getString(R.string.bound_map));
        mMapView.getMap().getOperationalLayers().add(mapImageLayer);
        serviceFeatureTable1 = new ServiceFeatureTable(ip +
                getResources().getString(R.string.bound_feature));
        listener();

        AutoCompleteTextView autoCompleteTextView=findViewById(R.id.editText);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.place_name));
        autoCompleteTextView.setAdapter(adapter);

        TextView search=findViewById(R.id.search);
        search.setOnClickListener(v -> {
            String target= String.valueOf(autoCompleteTextView.getText());
            search(target);
            autoCompleteTextView.getText().clear();
        });
    }

    private void search(String name){
        //关闭弹出框
        if (mCallout.isShowing()) {
            mCallout.dismiss();
        }

        mMapView.getGraphicsOverlays().clear();

        QueryParameters query = new QueryParameters();
        query.setWhereClause("ZLDWMC = '"+name+"'");
        final ListenableFuture<FeatureQueryResult> future= serviceFeatureTable1
                .queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
        future.addDoneListener(() -> {
            try {
                FeatureQueryResult result = future.get();
                Iterator<Feature> iterator = result.iterator();
                LinearLayout linearLayout =new LinearLayout(getApplicationContext());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                TextView calloutContent = new TextView(getApplicationContext());
                calloutContent.setTextColor(Color.BLACK);
                calloutContent.setSingleLine(false);
                calloutContent.setVerticalScrollBarEnabled(true);
                calloutContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
                calloutContent.setMovementMethod(new ScrollingMovementMethod());
                calloutContent.setLines(5);
                Feature feature;
                Toast.makeText(getApplicationContext(), "未找到", Toast.LENGTH_LONG).show();
                while (iterator.hasNext()) {
                    Toast.makeText(getApplicationContext(), "已找到", Toast.LENGTH_LONG).show();
                    feature = iterator.next();
                    GraphicsOverlay graphicsOverlay=new GraphicsOverlay();
                    SimpleFillSymbol simpleFillSymbol=new SimpleFillSymbol(SimpleFillSymbol.Style.NULL,Color.RED,new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 3));
                    graphicsOverlay.getGraphics().add(new Graphic(feature.getGeometry(),simpleFillSymbol));
                    mMapView.getGraphicsOverlays().add(graphicsOverlay);
                    Map<String, Object> attr = feature.getAttributes();
                    Set<String> keys = attr.keySet();
                    for (String key : keys) {
                        Object value = attr.get(key);
                        if (value instanceof GregorianCalendar) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.CHINA);
                            value = simpleDateFormat.format(((GregorianCalendar) value).getTime());
                        }
                        calloutContent.append(key + " | " + value + "\n");
                    }
                    linearLayout.addView(calloutContent);
                    Button button=new Button(getApplicationContext());
                    button.setText("评价分析");
                    if("昌吉市".equals(attr.get("ZLDWMC"))||"玛纳斯县".equals(attr.get("ZLDWMC"))){
                        button.setBackgroundColor(getResources().getColor(R.color.btn_active));
                        button.setTextColor(Color.WHITE);
                        button.setOnClickListener(v -> {
                            Intent intent=new Intent();
                            intent.setClass(getApplicationContext(),MainActivity.class);
                            intent.putExtra("name", String.valueOf(attr.get("ZLDWMC")));
                            intent.putExtra("ip",ip);
                            startActivity(intent);
                        });
                    }else {
                        button.setClickable(false);
                    }
                    linearLayout.addView(button);
                    Envelope envelope1 = feature.getGeometry().getExtent();
                    mMapView.setViewpointGeometryAsync(envelope1);
                    mCallout.setLocation(feature.getGeometry().getExtent().getCenter());
                    mCallout.setContent(linearLayout);
                    mCallout.show();

                }
            } catch (Exception e1) {
                Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e1.getMessage());
            }
        });
    }


    @SuppressLint("ClickableViewAccessibility")
    private void listener() {
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {

                //关闭弹出框
                if (mCallout.isShowing()) {
                    mCallout.dismiss();
                }

                mMapView.getGraphicsOverlays().clear();

                final Point clickPoint = mMapView
                        .screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));

                //查询参数设置
                QueryParameters query = new QueryParameters();
                query.setGeometry(clickPoint);
                query.setSpatialRelationship(QueryParameters.SpatialRelationship.WITHIN);
                final ListenableFuture<FeatureQueryResult> future= serviceFeatureTable1
                            .queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);


                future.addDoneListener(() -> {
                    try {
                        FeatureQueryResult result = future.get();
                        Iterator<Feature> iterator = result.iterator();
                        LinearLayout linearLayout =new LinearLayout(getApplicationContext());
                        linearLayout.setOrientation(LinearLayout.VERTICAL);
                        TextView calloutContent = new TextView(getApplicationContext());
                        calloutContent.setTextColor(Color.BLACK);
                        calloutContent.setSingleLine(false);
                        calloutContent.setVerticalScrollBarEnabled(true);
                        calloutContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
                        calloutContent.setMovementMethod(new ScrollingMovementMethod());
                        calloutContent.setLines(5);
                        Feature feature;

                        while (iterator.hasNext()) {
                            feature = iterator.next();
                            GraphicsOverlay graphicsOverlay=new GraphicsOverlay();
                            SimpleFillSymbol simpleFillSymbol=new SimpleFillSymbol(SimpleFillSymbol.Style.NULL,Color.RED,new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 3));
                            graphicsOverlay.getGraphics().add(new Graphic(feature.getGeometry(),simpleFillSymbol));
                            mMapView.getGraphicsOverlays().add(graphicsOverlay);
                            // create a Map of all available attributes as name value pairs
                            Map<String, Object> attr = feature.getAttributes();
                            Set<String> keys = attr.keySet();
                            for (String key : keys) {
                                Object value = attr.get(key);
                                if (value instanceof GregorianCalendar) {
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.CHINA);
                                    value = simpleDateFormat.format(((GregorianCalendar) value).getTime());
                                }
                                calloutContent.append(key + " | " + value + "\n");
                            }
                            linearLayout.addView(calloutContent);
                            Button button=new Button(getApplicationContext());
                            button.setText("评价分析");
                            if("昌吉市".equals(attr.get("ZLDWMC"))||"玛纳斯县".equals(attr.get("ZLDWMC"))){
                                button.setBackgroundColor(getResources().getColor(R.color.btn_active));
                                button.setTextColor(Color.WHITE);
                                button.setOnClickListener(v -> {
                                    Intent intent=new Intent();
                                    intent.setClass(getApplicationContext(),MainActivity.class);
                                    intent.putExtra("name", String.valueOf(attr.get("ZLDWMC")));
                                    intent.putExtra("ip",ip);
                                    startActivity(intent);
                                });
                            }else {
                                button.setClickable(false);
                            }
                            linearLayout.addView(button);
                            Envelope envelope1 = feature.getGeometry().getExtent();
                            mMapView.setViewpointGeometryAsync(envelope1);
                            mCallout.setLocation(clickPoint);
                            mCallout.setContent(linearLayout);
                            mCallout.show();
                        }
                    } catch (Exception e1) {
                        Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e1.getMessage());
                    }
                });

                return super.onSingleTapConfirmed(e);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.dispose();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.pause();
    }
}
